#!/bin/bash

##################################################################################
# author: Rajiv Ramnath
# this is for creating a spoof entry for your hosts file
# usage ./spoof.sh <edgehostname> <host>
# <edgehostname> can be the values below or a user provided name (can be customised)
# stg = a1.g.akamai-staging.net
# prod = a1.g.akamai.net
# etn1 = etn1.akamai.com
# etn2 = etn2.akamai.com
# etn3 = etn3.akamai.com
# etn4 = etn4.akamai.com
# etn5 = etn5.akamai.com
# etn6 = etn6.akamai.com
# etn7 = etn7.akamai.com
# etn8 = etn8.akamai.com
# etn9 = etn9.akamai.com
# foxstg = secure.fox.com.edgekey-staging.net
# foxprod = secure.fox.com.edgekey.net
# ffestg = qa.ffecentral.com.edgekey-staging.net
# ffeprod = qa.ffecentral.com.edgekey.net
# <host> is the hostname that needs to be spoofed 
##################################################################################

# debug: number of arguments
#echo "d: arguments = $*"

# step 1: 
# check if we have exactly 2 arguments

if test $# -ne 2 
then
	# wrong number of arguments - exit script
	echo "Usage: ./spoof.sh edgehost host"
	exit -1
fi

# step 2: 
# 2 arguments are found - set up the initial variables

edgehostname="$1"
spoofhost="$2"

#echo "d: edgehost - $edgehostname"
#echo "d: spoofhost - $spoofhost"

# step 3: 
# check the edgehostname with a "defined" list below
# this list is hardcoded for now
# it can be replaced with anything else

if [ "$edgehostname" = "etn1" ]
	then ehn="etn1.akamai.com"
elif [ "$edgehostname" = "etn2" ]
	then ehn="etn2.akamai.com"
elif [ "$edgehostname" = "etn3" ]
	then ehn="etn3.akamai.com"	
elif [ "$edgehostname" = "etn4" ]
	then ehn="etn4.akamai.com"
elif [ "$edgehostname" = "stg" ]
	then ehn="a1.g.akamai-staging.net"
elif [ "$edgehostname" = "prod" ]
	then ehn="a1.g.akamai.net"
elif [ "$edgehostname" = "foxstg" ]
	then ehn="secure.fox.com.edgekey-staging.net"
elif [ "$edgehostname" == "foxprod" ]
	then ehn="secure.fox.com.edgekey.net"
else
	ehn="NONE"
fi			

#echo "d: table match - $ehn"

# step 4:
# if the value of ehn is NONE, this means that
# it is not one of the predefined values
# hence use the value provided by the cmd line args

if [ "$ehn" = "NONE" ]
	then ehn="$1"
#	echo "d: setup ehn - $ehn"
fi

# step 5:
# do a dig to pull out a resolving ip
# this method pulls out only the first ip
# even though multiple ips are returned because of load balancing
# also verify that the field is not empty - most likely because of invalid hostname

ip=$(dig +short $ehn | egrep -iv "(akamai|edgesuite|edgekey)" | head -n1)

#echo "d: dig ip - $ip"

if [ "$ip" = "" ]
	then
	echo "Edge hostname not valid"
	exit -1

fi

# step 6:
# create the hostfile entry
echo "----------"
echo -e "$ip \t $spoofhost"
echo "----------"